<template>
  <div class="crm-opportunity">
    <el-card shadow="never">
      <template #header>
        <div class="crm-opportunity__header">
          <span>销售机会管理</span>
          <div>
            <el-button type="primary" size="small" @click="openCreate">新增</el-button>
            <el-button size="small" type="danger" :disabled="multipleSelection.length===0" @click="onBatchDelete">批量删除</el-button>
          </div>
        </div>
      </template>
      <el-form :inline="true" class="crm-opportunity__search" @submit.prevent>
        <el-form-item label="机会编号">
          <el-input v-model="query.opportunityCode" clearable placeholder="支持模糊" />
        </el-form-item>
        <el-form-item label="机会名称">
          <el-input v-model="query.opportunityName" clearable placeholder="支持模糊" />
        </el-form-item>
        <el-form-item label="客户">
          <el-select
            v-model="query.customerId"
            clearable
            filterable
            remote
            reserve-keyword
            :remote-method="remoteCustomer"
            :loading="loadingCustomer"
            placeholder="输入客户编码/名称"
            style="width: 200px"
          >
            <el-option v-for="c in customerOptions" :key="c.customerId" :label="`${c.customerCode} | ${c.customerName}`" :value="String(c.customerId)" />
          </el-select>
        </el-form-item>
        <el-form-item label="销售阶段">
          <el-select v-model="query.stage" placeholder="全部" clearable>
            <el-option value="INITIAL" label="初步接触" />
            <el-option value="REQUIREMENT" label="需求确认" />
            <el-option value="QUOTE" label="方案报价" />
            <el-option value="NEGOTIATE" label="谈判签约" />
            <el-option value="WIN" label="赢单" />
            <el-option value="LOSE" label="输单" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="query.status" placeholder="全部" clearable>
            <el-option value="ACTIVE" label="进行中" />
            <el-option value="WON" label="已赢单" />
            <el-option value="LOST" label="已输单" />
            <el-option value="CANCELLED" label="已取消" />
          </el-select>
        </el-form-item>
        <el-form-item label="机会来源">
          <el-input v-model="query.source" clearable placeholder="支持模糊" />
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="query.timeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始"
            end-placeholder="结束"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" @click="onSearch">查询</el-button>
          <el-button size="small" @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table :data="list" size="small" style="width: 100%" @selection-change="onSelectionChange">
        <el-table-column type="selection" width="48" />
        <el-table-column prop="opportunityCode" label="机会编号" min-width="140" />
        <el-table-column prop="opportunityName" label="机会名称" min-width="180" />
        <el-table-column prop="customerId" label="客户ID" min-width="120" />
        <el-table-column prop="stage" label="销售阶段" min-width="120">
          <template #default="{ row }">
            <el-tag v-if="row.stage === 'INITIAL'" type="info">初步接触</el-tag>
            <el-tag v-else-if="row.stage === 'REQUIREMENT'" type="">需求确认</el-tag>
            <el-tag v-else-if="row.stage === 'QUOTE'" type="warning">方案报价</el-tag>
            <el-tag v-else-if="row.stage === 'NEGOTIATE'" type="primary">谈判签约</el-tag>
            <el-tag v-else-if="row.stage === 'WIN'" type="success">赢单</el-tag>
            <el-tag v-else-if="row.stage === 'LOSE'" type="danger">输单</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="probability" label="成交概率(%)" min-width="100" />
        <el-table-column prop="expectedAmount" label="预计金额" min-width="120">
          <template #default="{ row }">
            {{ row.expectedAmount ? Number(row.expectedAmount).toFixed(2) : '0.00' }}
          </template>
        </el-table-column>
        <el-table-column prop="expectedDate" label="预计成交日期" min-width="120" />
        <el-table-column prop="status" label="状态" min-width="100">
          <template #default="{ row }">
            <el-tag v-if="row.status === 'ACTIVE'" type="success">进行中</el-tag>
            <el-tag v-else-if="row.status === 'WON'" type="success">已赢单</el-tag>
            <el-tag v-else-if="row.status === 'LOST'" type="danger">已输单</el-tag>
            <el-tag v-else-if="row.status === 'CANCELLED'" type="info">已取消</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="source" label="机会来源" min-width="120" />
        <el-table-column prop="createTime" label="创建时间" min-width="160" />
        <el-table-column label="操作" width="160" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="openEdit(row)">编辑</el-button>
            <el-popconfirm title="确认删除该销售机会？" @confirm="onDelete(row)">
              <template #reference>
                <el-button link type="danger" size="small">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <div class="crm-opportunity__pagination">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          :current-page="pageNum"
          @size-change="onSizeChange"
          @current-change="onPageChange"
        />
      </div>
    </el-card>

    <el-drawer v-model="drawerVisible" :with-header="true" :title="drawerTitle" size="600px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="机会编号" prop="opportunityCode">
          <el-input v-model="form.opportunityCode" maxlength="64" />
        </el-form-item>
        <el-form-item label="机会名称" prop="opportunityName">
          <el-input v-model="form.opportunityName" maxlength="200" />
        </el-form-item>
        <el-form-item label="客户" prop="customerId">
          <el-input
            v-model="form.customerNameDisplay"
            readonly
            placeholder="点击选择客户"
            style="width: 100%"
            @click="openCustomerSelector"
          >
            <template #append>
              <el-button @click="openCustomerSelector">选择客户</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="主要联系人" prop="contactId">
          <el-select v-model="form.contactId" clearable filterable placeholder="请选择联系人" style="width: 100%">
            <el-option v-for="c in contactOptions" :key="c.contactId" :label="`${c.contactName} | ${c.phone || ''}`" :value="String(c.contactId)" />
          </el-select>
        </el-form-item>
        <el-form-item label="销售阶段" prop="stage">
          <el-select v-model="form.stage" placeholder="请选择" style="width: 100%">
            <el-option value="INITIAL" label="初步接触" />
            <el-option value="REQUIREMENT" label="需求确认" />
            <el-option value="QUOTE" label="方案报价" />
            <el-option value="NEGOTIATE" label="谈判签约" />
            <el-option value="WIN" label="赢单" />
            <el-option value="LOSE" label="输单" />
          </el-select>
        </el-form-item>
        <el-form-item label="成交概率(%)" prop="probability">
          <el-input-number v-model="form.probability" :min="0" :max="100" style="width: 100%" />
        </el-form-item>
        <el-form-item label="预计金额" prop="expectedAmount">
          <el-input-number v-model="form.expectedAmount" :precision="2" :min="0" style="width: 100%" />
        </el-form-item>
        <el-form-item label="预计成交日期" prop="expectedDate">
          <el-date-picker v-model="form.expectedDate" type="date" placeholder="选择日期" value-format="YYYY-MM-DD" style="width: 100%" />
        </el-form-item>
        <el-form-item label="机会来源" prop="source">
          <el-input v-model="form.source" maxlength="32" />
        </el-form-item>
        <el-form-item label="竞争对手信息" prop="competitorInfo">
          <el-input v-model="form.competitorInfo" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item label="机会描述" prop="description">
          <el-input v-model="form.description" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择" style="width: 100%">
            <el-option value="ACTIVE" label="进行中" />
            <el-option value="WON" label="已赢单" />
            <el-option value="LOST" label="已输单" />
            <el-option value="CANCELLED" label="已取消" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div style="flex: 1; text-align: center">
          <el-button @click="drawerVisible = false">取消</el-button>
          <el-button type="primary" :loading="submitLoading" @click="submitForm">保存</el-button>
        </div>
      </template>
    </el-drawer>

    <!-- 客户选择器 -->
    <CrmCustomerSelector v-model="customerSelectorVisible" @confirm="handleCustomerSelected" />
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, watch } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import {
  pageOpportunity,
  createOpportunity,
  updateOpportunity,
  getOpportunity,
  deleteOpportunity,
  deleteOpportunityBatch
} from '@/api/crm/opportunity'
import { pageCustomer, getCustomer } from '@/api/crm/customer'
import { listContactByCustomer } from '@/api/crm/contact'
import CrmCustomerSelector from '@/components/CrmCustomerSelector/index.vue'
import { ElMessage } from 'element-plus'

interface OpportunityForm {
  opportunityId?: string
  opportunityCode: string
  opportunityName: string
  customerId: string
  contactId?: string
  ownerUserId?: string
  ownerDeptId?: string
  stage: 'INITIAL' | 'REQUIREMENT' | 'QUOTE' | 'NEGOTIATE' | 'WIN' | 'LOSE'
  probability?: number
  expectedAmount?: number
  expectedDate?: string
  actualAmount?: number
  actualDate?: string
  source?: string
  competitorInfo?: string
  description?: string
  status: 'ACTIVE' | 'WON' | 'LOST' | 'CANCELLED'
  winReason?: string
  loseReason?: string
  remark?: string
}

const list = ref<any[]>([])
const total = ref(0)
const pageNum = ref(1)
const pageSize = ref(10)
const query = reactive<{
  opportunityCode?: string
  opportunityName?: string
  customerId?: string
  stage?: string
  status?: string
  source?: string
  timeRange?: string[]
}>({
  opportunityCode: '',
  opportunityName: '',
  customerId: '',
  stage: '',
  status: '',
  source: '',
  timeRange: []
})
const multipleSelection = ref<any[]>([])

const drawerVisible = ref(false)
const isEdit = ref(false)
const drawerTitle = ref('新增销售机会')
const formRef = ref<FormInstance>()
const form = reactive<OpportunityForm & { customerNameDisplay?: string }>({
  opportunityCode: '',
  opportunityName: '',
  customerId: '',
  customerNameDisplay: '',
  contactId: '',
  ownerUserId: '',
  ownerDeptId: '',
  stage: 'INITIAL',
  probability: 0,
  expectedAmount: undefined,
  expectedDate: '',
  actualAmount: undefined,
  actualDate: '',
  source: '',
  competitorInfo: '',
  description: '',
  status: 'ACTIVE',
  winReason: '',
  loseReason: '',
  remark: ''
})
const rules: FormRules = {
  opportunityCode: [{ required: true, message: '请输入机会编号', trigger: 'blur' }],
  opportunityName: [{ required: true, message: '请输入机会名称', trigger: 'blur' }],
  customerId: [{ required: true, message: '请选择客户', trigger: 'change' }],
  stage: [{ required: true, message: '请选择销售阶段', trigger: 'change' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}
const submitLoading = ref(false)

// 客户选择器
const customerSelectorVisible = ref(false)

const openCustomerSelector = () => {
  customerSelectorVisible.value = true
}

const handleCustomerSelected = (customer: any) => {
  form.customerId = String(customer.customerId)
  form.customerNameDisplay = `${customer.customerCode} | ${customer.customerName}`
  // 客户改变后，重新加载联系人
  if (form.customerId) {
    loadContacts(form.customerId)
  }
}

// 下拉选项
const contactOptions = ref<any[]>([])

const loadContacts = async (customerId: string) => {
  if (!customerId) {
    contactOptions.value = []
    return
  }
  try {
    const res = await listContactByCustomer(customerId)
    contactOptions.value = res?.data || []
  } catch (error) {
    console.error('加载联系人列表失败:', error)
  }
}

watch(() => form.customerId, (val) => {
  if (val) {
    loadContacts(val)
  } else {
    contactOptions.value = []
    form.contactId = ''
  }
})

const load = async () => {
  const res = await pageOpportunity({
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    opportunityCode: query.opportunityCode || undefined,
    opportunityName: query.opportunityName || undefined,
    customerId: query.customerId || undefined,
    stage: query.stage || undefined,
    status: query.status || undefined,
    source: query.source || undefined,
    startTime:
      Array.isArray(query.timeRange) && query.timeRange.length === 2 ? query.timeRange[0] : undefined,
    endTime:
      Array.isArray(query.timeRange) && query.timeRange.length === 2 ? query.timeRange[1] : undefined
  })
  list.value = res?.data?.records || []
  total.value = res?.data?.total || 0
}

const onPageChange = (p: number) => {
  pageNum.value = p
  load()
}
const onSizeChange = (s: number) => {
  pageSize.value = s
  pageNum.value = 1
  load()
}

const onSearch = () => {
  pageNum.value = 1
  load()
}

const onReset = () => {
  query.opportunityCode = ''
  query.opportunityName = ''
  query.customerId = ''
  query.stage = ''
  query.status = ''
  query.source = ''
  query.timeRange = []
  onSearch()
}

const resetForm = () => {
  form.opportunityId = undefined
  form.opportunityCode = ''
  form.opportunityName = ''
  form.customerId = ''
  form.customerNameDisplay = ''
  form.contactId = ''
  form.ownerUserId = ''
  form.ownerDeptId = ''
  form.stage = 'INITIAL'
  form.probability = 0
  form.expectedAmount = undefined
  form.expectedDate = ''
  form.actualAmount = undefined
  form.actualDate = ''
  form.source = ''
  form.competitorInfo = ''
  form.description = ''
  form.status = 'ACTIVE'
  form.winReason = ''
  form.loseReason = ''
  form.remark = ''
  contactOptions.value = []
}

const openCreate = () => {
  isEdit.value = false
  drawerTitle.value = '新增销售机会'
  resetForm()
  drawerVisible.value = true
}

const openEdit = async (row: any) => {
  isEdit.value = true
  drawerTitle.value = '编辑销售机会'
  resetForm()
  try {
    const res = await getOpportunity(String(row.opportunityId))
    const data = res?.data || {}
    Object.assign(form, {
      ...data,
      opportunityId: String(data.opportunityId),
      customerId: String(data.customerId),
      contactId: data.contactId ? String(data.contactId) : '',
      ownerUserId: data.ownerUserId ? String(data.ownerUserId) : '',
      ownerDeptId: data.ownerDeptId ? String(data.ownerDeptId) : '',
      expectedDate: data.expectedDate ? String(data.expectedDate) : '',
      actualDate: data.actualDate ? String(data.actualDate) : ''
    })
    // 加载客户名称用于显示
    if (data.customerId) {
      try {
        const customerRes = await getCustomer(String(data.customerId))
        const customer = customerRes?.data
        if (customer) {
          form.customerNameDisplay = `${customer.customerCode} | ${customer.customerName}`
        }
      } catch (error) {
        console.error('加载客户信息失败:', error)
      }
      await loadContacts(String(data.customerId))
    }
    drawerVisible.value = true
  } catch (error) {
    ElMessage.error('加载销售机会信息失败')
  }
}

const submitForm = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        const payload = {
          ...form,
          customerId: String(form.customerId),
          contactId: form.contactId ? String(form.contactId) : undefined,
          ownerUserId: form.ownerUserId ? String(form.ownerUserId) : undefined,
          ownerDeptId: form.ownerDeptId ? String(form.ownerDeptId) : undefined
        }
        if (isEdit.value) {
          await updateOpportunity(String(form.opportunityId!), payload as any)
          ElMessage.success('更新成功')
        } else {
          await createOpportunity(payload as any)
          ElMessage.success('新增成功')
        }
        drawerVisible.value = false
        load()
      } catch (error: any) {
        ElMessage.error(error?.message || '保存失败')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

const onDelete = async (row: any) => {
  try {
    await deleteOpportunity(String(row.opportunityId))
    ElMessage.success('删除成功')
    load()
  } catch (error: any) {
    ElMessage.error(error?.message || '删除失败')
  }
}

const onBatchDelete = async () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请选择要删除的数据')
    return
  }
  try {
    const ids = multipleSelection.value.map((row: any) => String(row.opportunityId))
    await deleteOpportunityBatch(ids)
    ElMessage.success('批量删除成功')
    load()
  } catch (error: any) {
    ElMessage.error(error?.message || '批量删除失败')
  }
}

const onSelectionChange = (selection: any[]) => {
  multipleSelection.value = selection
}

onMounted(() => {
  load()
})
</script>

<style scoped lang="scss">
.crm-opportunity {
  &__header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  &__search {
    margin-bottom: 12px;
  }
  &__pagination {
    margin-top: 12px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>


